package com.jeff.utils.concurrent;

import android.os.Handler;
import android.os.Looper;

/**
 * author：duff
 * version：1.0.0
 * date：2017/8/27
 * desc：多任务执行调度器
 */
public class TaskSchedule {
    private static Handler mHandler = new Handler(Looper.getMainLooper());
    private static ThreadPool mThreadPool = new ThreadPool("task_scheduler");

    /**
     * 以轻量级的方式执行一个异步任务
     *
     * @param backgroundTaskRunnable 异步任务
     */
    public static void execute(final Runnable backgroundTaskRunnable) {
        if (backgroundTaskRunnable != null) {
            mThreadPool.addTask(backgroundTaskRunnable);
        }
    }

    public static void execute(final Runnable backgroundRunnable, final Runnable foregroundRunnable) {
        mThreadPool.addTask(new Runnable() {
            @Override
            public void run() {
                if (backgroundRunnable != null) {
                    backgroundRunnable.run();
                }

                if (foregroundRunnable != null) {
                    mHandler.post(foregroundRunnable);
                }
            }
        });
    }


    public static <IN, OUT> void execute(final Task<IN, OUT> task) {
        exec(task);
    }

    private static <IN, OUT> void exec(final Task<IN, OUT> task) {
        if (task != null) {
            mThreadPool.addTask(new Runnable() {
                @Override
                public void run() {
                    final OUT out = task.onBackground(task.mInput);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            task.onForeground(out);
                        }
                    });

                }
            });
        }
    }

}

